import json
from datetime import datetime, timedelta
import logging

logger = logging.getLogger(__name__)
class LocalWebDashboard:
    def get_latest_prices(self, limit=50):
        if not self.redis_client:
            return []

        try:
            keys = self.redis_client.keys('cnhnb_price:*')
            if not keys:
                return []

            data_list = []
            for key in keys:
                try:
                    data = self.redis_client.get(key)
                    if data:
                        item = json.loads(data)
                        data_list.append(item)
                except Exception as e:
                    logger.warning(f"解析数据失败 {key}: {e}")

            # 按时间倒序
            data_list.sort(key=lambda x: x.get('timestamp', 0), reverse=True)

            # 去重：用(产品名, 价格, 产地, 日期)做唯一标识
            seen = set()
            unique_data = []
            for item in data_list:
                uniq_key = (item.get('name'), item.get('price_value'), item.get('location'), item.get('date'))
                if uniq_key not in seen:
                    seen.add(uniq_key)
                    unique_data.append(item)
                if len(unique_data) >= limit:
                    break

            return unique_data

        except Exception as e:
            logger.error(f"获取价格数据失败: {e}")
            return []

    def get_system_status(self):
        status = {
            'redis_connected': False,
            'spider_running': False,
            'data_count': 0,
            'last_update': None
        }
        try:
            if self.redis_client:
                self.redis_client.ping()
                status['redis_connected'] = True
                keys = self.redis_client.keys('cnhnb_price:*')
                status['data_count'] = len(keys)
                if keys:
                    latest_key = max(keys, key=lambda k: self.redis_client.get(k))
                    latest_data = self.redis_client.get(latest_key)
                    if latest_data:
                        item = json.loads(latest_data)
                        status['last_update'] = item.get('crawl_timestamp')
                        # 判断最新数据是否在1分钟内
                        if item.get('crawl_timestamp'):
                            try:
                                last_time = datetime.fromisoformat(item['crawl_timestamp'])
                                if datetime.now() - last_time < timedelta(minutes=1):
                                    status['spider_running'] = True
                            except Exception:
                                pass
        except Exception as e:
            logger.error(f"检查Redis状态失败: {e}")
        return status 